package cn.y.operation.framework.iconfig.i18n;

import cn.y.operation.framework.utils.dev.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * @ClassName: MyLocaleResolver
 * @author: 叶子豪
 * @create: 2020-10-19 20:20
 */
public class MyLocaleResolver implements LocaleResolver {
    @Value("${myLanguage}")
    private Locale myLanguage;

    /*
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        // 默认语言
        slr.setDefaultLocale(myLanguage);
        return slr;
    }*/

    // 自定义区域解析方式，点击LocaleResolver部分，按ALT+ENTRE,可重写resolveLocale和setLocale方法
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        // 获取页面手动切换传递的语言参数l
        String lan = request.getParameter("lan");
        Object lans = request.getSession().getAttribute("lan");
        String lan2 = lans == null ? null : lans.toString();
        // 获取请求头自动传递的语言参数Accept-Language
        String header = request.getHeader("Accept-Language");
        Locale locale;
        String[] split;
        // 如果手动切换参数不为空，就根据手动参数进行语言切换，否则默认根据请求头信息切换
        if (StringUtils.isNotEmpty(lan)) {
            split = lan.split("_");
            locale = new Locale(split[0], split[1]);
        } else if (StringUtils.isNotEmpty(lan2)) {
            split = lan2.split("_");
            locale = new Locale(split[0], split[1]);
        } else {
            // Accept-Language: ko en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
            /*String[] splits = header.split(",");
            String[] split = splits[0].split("-");
            locale = new Locale(split[0], split[1]);*/
            locale = myLanguage;
        }
        request.getSession().setAttribute("lan", locale);
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        throw new UnsupportedOperationException("Cannot change HTTP accept header - use a different locale resolution strategy");
    }
}
